#include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string lowercase(string str) 
{
    for (int i = 0; i < str.length(); i++) 
        str[i] = tolower(str[i]);
    return str;
}

void makecdf(char* prefix, int maxk, char* naive)
{
    char filename[1024];
    string line;
    int k, m, r;
    double nrho, srho, ratio;
    ifstream nfile, sfile;
    ofstream out;
    vector<vector<double> > ratios(maxk + 1, vector<double>(0)); 

    out.open("temp.txt");

    for(k = 2; k <= maxk; ++k)
    {
	sprintf(filename, "%s1-DENSITY.txt", naive);
	nfile.open(filename);
	sprintf(filename, "%s%dBINS-1-DENSITY.txt", prefix, k);
	sfile.open(filename);

	if (nfile.is_open() && sfile.is_open())
	{
	    m = 0;
	    while (getline(nfile, line))
	    {
		sscanf(line.c_str(), "%lf", &nrho);
		getline(sfile, line);
		sscanf(line.c_str(), "%lf", &srho);

		ratio = nrho/srho;
		ratios[k].push_back(ratio);
		m++;
	    }
	    sort(ratios[k].begin(), ratios[k].begin() + m);
	}
	nfile.close(); sfile.close();
    }

    for(r = 0; r < m; ++r)
    {	
	out << double(r)/m ;
	for(k = 2; k <= maxk; ++k)
	    out << "\t" << ratios[k][r]; 
	out << endl;
    }

    out.close();

    out.open("plot.p");
    out << "set term postscript eps color\n";
    out << "set output \"" << prefix << "varyk-cdf.eps\"\n";
    out << "set xlabel 'density ratio'\n";
    out << "set ylabel 'cumulative probability'\n";
    out << "set key right bottom\n";
    out << "set key box\n";
    out << "set size .75,.75\n";

    string plot = "plot \"temp.txt\" using 2:1 title 'k = 2' with lines";
    char part[128];
    //for(int k = 3; k <= maxk; ++k)
    for(int k = 4; k <= 8; k+=2)
    {
	sprintf(part,  ", \"temp.txt\" using %d:1 title 'k = %d' with lines", k, k);
	plot += string(part);
    }
    out << plot << endl;
    out.close();

    if (system("gnuplot plot.p"))
        cout << "Error with plotting.\n";
    char command[1024];
    sprintf(command, "convert -density 500 %svaryk-cdf.eps %svaryk-cdf.pdf", prefix, prefix);
    if (system(command))
        cout << "Error converting to pdf.\n";
}

void makestats(char* prefix, int maxk, char* naive, int repeats)
{
    char filename[1024];
    string line;
    int k, m, r;
    double srho, nrho, rho, ratio, sumratio;
    ifstream nfile, sfile;
    ofstream out;
    double max = 0.0, min = 1000000000.0;
    double maxTotal, avgTotal;

    out.open("temp.txt");

    for(k = 2; k <= maxk; ++k)
    {
	maxTotal = 0.0; avgTotal = 0.0;
	for(r = 1; r <= repeats; ++r)
	{
	    // measure density stats
	    sprintf(filename, "%s%d-DENSITY.txt", naive, r);
	    nfile.open(filename);
	    sprintf(filename, "%s%dBINS-%d-DENSITY.txt", prefix, k, r);
	    sfile.open(filename);
	    sumratio = 0.0; m = 0;
	    max = 0.0; 
	    if (nfile.is_open() && sfile.is_open())
	    {
		while (getline(nfile, line))
		{
		    sscanf(line.c_str(), "%lf", &nrho);
		    getline(sfile, line);
		    sscanf(line.c_str(), "%lf", &srho);
		    
		    ratio = nrho/srho;
		    if (ratio > max)
		    {
			max = ratio;
		    }

		    sumratio += ratio;
		    m++;
		}
		sfile.close();
		nfile.close();
	    }
	    maxTotal += max;
	    avgTotal += sumratio/m;
	}
	out << k << "\t" << maxTotal/repeats << "\t" << avgTotal/repeats << endl;
    }

    out.close();
}

void makeplot(char* prefix, string stat)
{
    ofstream outfile;
    outfile.open("plot.p");
    outfile << "set term postscript eps color\n";
    if (stat[0] == 'M')
	outfile << "set output \"" << prefix << "varyk-max.eps\"\n";
    else
	outfile << "set output \"" << prefix << "varyk-avg.eps\"\n";
    outfile << "set xlabel 'k'\n";
    outfile << "set ylabel 'density ratio'\n";
    outfile << "set key left top\n";
    outfile << "set key box\n";
    outfile << "set size .75,.75\n";
    outfile << "set style line 1 lw 3 lc rgb \"red\"\n";
    outfile << "set style line 2 lc rgb \"blue\" lw 2\n";
    //outfile << "set style line 3 lc rgb \"brown\" lw 2\n";
    //outfile << "set style line 4 lc rgb \"black\" lw 2\n";
    //outfile << "set style line 5 lc rgb \"#888888\" lw 2\n";
    //outfile << "set style line 6 lc rgb \"#BBBBBB\" lw 2\n";
    //if (data[0] == 'T')
    //{
    //	outfile << "set logscale y\n";
	//outfile << "set xrange [:.1]\n";
    //}
    //else
    //{
    //outfile << "set yrange [0:]\n";
    //}
    
    // for plotting both separately:
    //outfile << "plot \"" << filenameN << "\" using 1 title 'Naive' ls 1 with linespoints, \"" << filenameS << "\" using 1 title 'Streaming' ls 2 with linespoints\n";

    // for plotting the ratio of the two:
    //outfile << "plot \"<paste " << filenameN << " " <<  filenameS << "\" using ($1/$2) title 'Density ratio' ls 1 with linespoints\n";

    if (stat[0] == 'M')
	outfile << "plot \"temp.txt\" using 1:2 title 'Max ratio' ls 1 with linespoints" << endl;
    else
	outfile << "plot \"temp.txt\" using 1:3 title 'Avg ratio' ls 1 with linespoints" << endl;

    outfile.close();

    if (system("gnuplot plot.p"))
	cout << "Error with plotting.\n";
    char command[1024];

    if (stat[0] == 'M')
	sprintf(command, "convert -density 500 %svaryk-max.eps %svaryk-max.pdf", prefix, prefix);
    else
	sprintf(command, "convert -density 500 %svaryk-avg.eps %svaryk-avg.pdf", prefix, prefix);

    if (system(command))
	cout << "Error converting to pdf.\n";
}

int main(int argc, char** argv)
{
    if (argc < 5)
    {
	cout << "Usage: makeplot filenameprefix maxk naive repeats" << endl;
	return 0;
    }

    makestats(argv[1], atoi(argv[2]), argv[3], atoi(argv[4]));
    makeplot(argv[1], "MAX");
    makeplot(argv[1], "AVG");

    makecdf(argv[1], atoi(argv[2]), argv[3]);

    return 0;
}
